package light.head.controller.oa;

import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.AlbumDAO;
import light.head.dao.oa.PhotoDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.Album;
import light.head.model.Photo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = Url.C_PHOTO)
public class PhotoController extends SupporterController{
	

	private final static String documentintInfo_file = "upload/photo/";
	private PhotoDAO photoDAO;
	private AlbumDAO albumDAO;
	private OrganDAO organDAO;

	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.ALBUM_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
			Map<String, String> map = createQueryMapByParmName(request, Parm.OC);
			Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
			if (albumDAO.findByMap(organDAO.getSonCodeList(oc), map, pb) == RESULT.SUCCESS) {
				Album al = null;
				for (Object o : pb.getResultList()) {
					al = (Album) o;
					List<Photo> ph = photoDAO.findByAlc(al.getCode());
					al.setPhotoList(ph);
//					if (ph.size() != 0){
//						request.setAttribute(Parm.LIST, ph.get(0));
//					}
				}
				
				request.setAttribute(Parm.PAGE_BEAN, pb);
			}
			return new ModelAndView(Url.ALBUM_LIST);
	}
	
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			Album album = albumDAO.get(Integer.parseInt(code));
			request.setAttribute(Parm.ALBUM, album);
		}
		return new ModelAndView(Url.ALBUM_EDIT);
	}

	@Transactional
	@RequestMapping(value = Url.SAVE)
	public void save(Album album, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (null == album.getCode()) {
			album.setDeleted(false);
			album.setCu(cu_code(request));
			album.setOc(cu_organCode(request));
			result = albumDAO.add(album);
			
		} else {
			result = albumDAO.upd(album);
		}
		
		if (RESULT.SUCCESS == result) {
			print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.DELETE)
	public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Photo p = photoDAO.get(Integer.parseInt(code));
		p.setDeleted(true);
		if (photoDAO.upd(p) == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.DELETE_ALBUM)
	public void deleteAlbum(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Album a = albumDAO.get(Integer.parseInt(code));
		a.setDeleted(true);
		if (photoDAO.upd(a) == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.EDITALBUM)
	public ModelAndView editAlbum(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			Album album = albumDAO.get(Integer.parseInt(code));
			List<Photo> photoList = photoDAO.findByAlc(album.getCode());
			album.setPhotoList(photoList);
			request.setAttribute(Parm.ALBUM, album);
		}
		return new ModelAndView(Url.PHOTO_EDITALBUM);
	}
	
	
	@RequestMapping(value = Url.PHOTOSHOW)
	public ModelAndView photoShow(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			Photo p = photoDAO.get(Integer.parseInt(code));
			request.setAttribute(Parm.PHOTO, p);
		}
		return new ModelAndView(Url.PHOTO_SHOW);
	}

	@RequestMapping(value = Url.SAVEALBUN)
	public void saveAlbum(Album album, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (null == album.getCode()) {
			album.setDeleted(false);
			album.setCt(new Date());
			album.setCu(cu_code(request));
			album.setOc(cu_organCode(request));
			result = albumDAO.add(album);
		}else {
			result = albumDAO.upd(album);
		}
		if (RESULT.SUCCESS == result) {
			print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.SAVEP)
	public void saveP(Photo p,HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		
		if (p.getCode() == null){
			print(response, Msg.EXISTS);
			return;
		}
		Photo p1 = photoDAO.get(p.getCode());
		Album al = albumDAO.get(p1.getAlc());
		List<Photo> photoList = photoDAO.findByAlc(al.getCode());
		for (Photo p2 : photoList) {
			if (p2 != null && (p2.getCover() != false || p2.getCover() == null )) {
				p2.setCover(false);
				photoDAO.upd(p2);
			}
		}
		p1.setCover(true);
		result = photoDAO.upd(p1);
		al.setUuid(p1.getUuid());
		result = albumDAO.upd(al);
		
		
		if (RESULT.SUCCESS == result) {
			print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}
	

	@RequestMapping(value = Url.QUERYPHOTO)
	public ModelAndView queryPhoto(Integer alc, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (alc != null) {
			Album a = albumDAO.get(alc);
			List<Photo> photoList = photoDAO.findByAlc(alc);
			a.setPhotoList(photoList);
			request.setAttribute(Parm.LIST, a);
			request.setAttribute(Parm.ALC, alc);
		}
		return new ModelAndView(Url.PHOTO_LIST);
	}
	
	@Transactional
	@RequestMapping(Url.UPLOADS)
	public void uploads(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequestd = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequestd.getFiles("files");
		String alc = request.getParameter(Parm.CODE);
		StringBuffer result = new StringBuffer("");
		if (null != files && files.size() > 0) {

			String name = null;
			String ext = null;
			String uuid = null;
			String path = null;
			String savePath = null;
			UUID u = null;

			for (MultipartFile mf : files) {
				name = mf.getOriginalFilename();
				System.out.println(mf.getOriginalFilename() + "--" + mf.getName());
				if (isNotNull(name)) {
					ext = name.substring(name.lastIndexOf('.') + 1);
					if (!ext.toUpperCase().equals(Sys.JPG)
							&& !ext.toUpperCase().equals(Sys.JPEG)
							&& !ext.toUpperCase().equals(Sys.BMP)
							&& !ext.toUpperCase().equals(Sys.PNG)) {
						print(response, Msg.J_FILE_TYPE_ERROR);
						return;
					}
					name = name.substring(0, name.lastIndexOf('.'));

					u = UUID.randomUUID();
					uuid = u.toString().replace("-", "");
					path = documentintInfo_file + uuid + Sys.DOT + ext;
					savePath = ConfigParm.getProjectPath() + path;
					FileOutputStream fo;
					int size = 0;
					try {
						fo = new FileOutputStream(savePath);
						size = mf.getBytes().length;
						fo.write(mf.getBytes());
						fo.close();
					} catch (Exception e) {
						print(response, Msg.ERROR);
						e.printStackTrace();
					}
					
					Photo p = new Photo();
					p.setDeleted(false);
					p.setExt(ext);
					p.setName(name);
					p.setCt(new Date());
					p.setCu(cu_code(request));
					p.setAlc(Integer.parseInt(alc));
					p.setSize(size);
					p.setUuid(path);
					p.setOc(cu_organCode(request));
					photoDAO.add(p);
					result.append("{\"code\":\"" + p.getCode() + "\"},");
				}
			}
			result.insert(0, "{\"result\":\"success\",\"list\":[").deleteCharAt(result.length() - 1).append("]}");
			print(response, result.toString());
		} else {
			result.append("{\"result\":\"not_find_file\"}");
		}
	}
	@Autowired
	public void setPhotoDAO(PhotoDAO photoDAO) {
		this.photoDAO = photoDAO;
	}
	@Autowired
	public void setAlbumDAO(AlbumDAO albumDAO) {
		this.albumDAO = albumDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
}
